package com.jz.community.modulemine.myCard.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.base.BaseX5WebActivity;
import com.jz.community.basecomm.bean.BaseResponseInfo;
import com.jz.community.basecomm.bean.baseCardInfo.BaseCardInfo;
import com.jz.community.basecomm.constant.HtmlConstant;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseImageLoaderUtils;
import com.jz.community.basecomm.utils.JsonUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.integral.task.GetCardBalanceTask;
import com.jz.community.modulemine.money.bean.MoneyInfoBean;
import com.jz.community.modulemine.money.ui.CardMoneyHistoryActivity;
import com.jz.community.modulemine.money.ui.MoneyExchangeActivity;
import com.jz.community.modulemine.money.ui.MoneyPurchaseActivity;
import com.jz.community.modulemine.money.ui.MoneyRechargeActivity;
import com.jz.community.modulemine.myCard.task.CardDeleteTask;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Tony.Fan on 2018/8/22 17:19
 */
public class CardDetailActivity extends BaseMvpActivity {


    @BindView(R2.id.title_back_left)
    ImageView titleBackLeft;
    @BindView(R2.id.title_name)
    TextView titleName;
    @BindView(R2.id.title_right)
    TextView titleRight;
    @BindView(R2.id.title_right_iv)
    ImageView titleRightIv;
    @BindView(R2.id.title_toolbar)
    Toolbar titleToolbar;
    @BindView(R2.id.card_detail_logo)
    ImageView cardDetailLogo;
    @BindView(R2.id.card_detail_img)
    CircleImageView cardDetailImg;
    @BindView(R2.id.card_detail_name)
    TextView cardDetailName;
    @BindView(R2.id.card_detail_money)
    TextView cardDetailMoney;
    @BindView(R2.id.card_detail_money_ll)
    LinearLayout cardDetailMoneyLl;
    @BindView(R2.id.card_detail_num)
    TextView cardDetailNum;
    @BindView(R2.id.card_detail_date)
    TextView cardDetailDate;
    @BindView(R2.id.card_detail_code)
    ImageView cardDetailCode;
    @BindView(R2.id.card_detail_parent)
    CardView cardDetailParent;
    @BindView(R2.id.card_detail_btn_charge)
    TextView cardDetailBtnCharge;
    @BindView(R2.id.card_detail_btn_use)
    TextView cardDetailBtnUse;
    @BindView(R2.id.card_detail_btn_ll1)
    LinearLayout cardDetailBtnLl1;
    @BindView(R2.id.card_detail_btn_use2)
    TextView cardDetailBtnUse2;
    @BindView(R2.id.card_detail_btn_ll2)
    LinearLayout cardDetailBtnLl2;
    @BindView(R2.id.card_detail_help_rl)
    RelativeLayout cardDetailHelpRl;
    @BindView(R2.id.card_detail_detail_rl)
    RelativeLayout cardDetailDetailRl;
    @BindView(R2.id.card_detail_detail_line)
    ImageView cardDetailDetailLine;
    @BindView(R2.id.card_detail_recharge_rl)
    RelativeLayout cardDetailRechargeRl;
    @BindView(R2.id.card_detail_recharge_line)
    ImageView cardDetailRechargeLine;
    @BindView(R2.id.card_detail_purchase_rl)
    RelativeLayout cardDetailPurchaseRl;
    @BindView(R2.id.card_detail_purchase_line)
    ImageView cardDetailPurchaseLine;
    @BindView(R2.id.card_detail_shop_rl)
    RelativeLayout cardDetailShopRl;
    @BindView(R2.id.card_detail_shop_line)
    ImageView cardDetailShopLine;
    @BindView(R2.id.card_detail_father)
    LinearLayout cardDetailFather;
    @BindView(R2.id.card_detail_delete)
    TextView cardDetailDelete;

    private BaseCardInfo cardDetailInfo;
    private String httpCardUrl;


    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(AppEvent message) {
        if (message.tag == EventConfig.REFRESH_MONEY_DETAIL) {
            getCardBalance();
        }
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(titleToolbar);
        titleName.setText("卡详情");
    }

    @Override
    protected void addListener() {
        super.addListener();
        titleBackLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //二维码
        cardDetailCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("cardno", cardDetailInfo.getCardno());
                bundle.putString("cardId", cardDetailInfo.getId());
                bundle.putInt("cardType", cardDetailInfo.getCardtype());
                RouterCommonUtils.startParamsActivity(RouterIntentConstant.CARD_SCAN, bundle);
            }
        });
        //充值
        cardDetailBtnCharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, MoneyRechargeActivity.class);
                if (!RxDataTool.isNullString(cardDetailInfo.getAmount() + "")) {
                    intent.putExtra("myMoney", cardDetailInfo.getAmount() + "");
                } else {
                    intent.putExtra("myMoney", "0");
                }
                startActivity(intent);

            }
        });

        //去使用
        cardDetailBtnUse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cardDetailInfo.getCardtype() == 999 || cardDetailInfo.getCardtype() == 2) {
                    Bundle bundle = new Bundle();
                    bundle.putString("cardno", cardDetailInfo.getCardno());
                    bundle.putString("cardId", cardDetailInfo.getId());
                    bundle.putInt("cardType", cardDetailInfo.getCardtype());
                    RouterCommonUtils.startParamsActivity(RouterIntentConstant.CARD_SCAN, bundle);
                } else if (cardDetailInfo.getCardtype() == 0) {
                    SHelper.vis(cardDetailBtnLl2);
                    SHelper.gone(cardDetailBtnUse, cardDetailBtnLl1);
                    cardDetailBtnUse2.setText(cardDetailInfo.getCardpwd());
                } else {
                    startActivity(new Intent(CardDetailActivity.this, BaseX5WebActivity.class)
                            .putExtra("url", httpCardUrl)
                            .putExtra("title", cardDetailInfo.getBrand()));
                }
            }
        });

        //使用帮助
        cardDetailHelpRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cardDetailInfo.getCardtype() == 999) {
                    startActivity(new Intent(CardDetailActivity.this, BaseX5WebActivity.class)
                            .putExtra("url", HtmlConstant.CARD_HTML_SQRE_URL)
                            .putExtra("title", "帮助"));
                } else {
                    startActivity(new Intent(CardDetailActivity.this, BaseX5WebActivity.class)
                            .putExtra("url", HtmlConstant.CARD_HTML_URL + cardDetailInfo.getProductId())
                            .putExtra("title", "帮助"));
                }
            }
        });

        //交易明细
        cardDetailDetailRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, CardMoneyHistoryActivity.class);
                startActivity(intent);
            }
        });

        //卡兑换
        cardDetailRechargeRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, MoneyExchangeActivity.class);
                startActivity(intent);
            }
        });

        //企业采购
        cardDetailPurchaseRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mActivity, MoneyPurchaseActivity.class);
                intent.putExtra("fromType", 0);
                startActivity(intent);
            }
        });

        //卡多多
        cardDetailShopRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.CARD_HOME);
            }
        });

        //删除卡片
        cardDetailDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int cardType = cardDetailInfo.getCardtype();
                if (cardType == 0 || cardType == 1) {
                    showDeleteDialog(cardDetailInfo.getId() + "");
                }
            }
        });
    }

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_card_detail;
    }

    @Override
    protected void initDatas() {
        super.initDatas();
        cardDetailInfo = JsonUtils.parseObject(getIntent().getStringExtra("cardInfo"), BaseCardInfo.class);
        EventBus.getDefault().register(this);
        showCardDetailInfo();
        handleCardStatus();
    }

    /**
     * 卡包余额
     */
    private void getCardBalance() {
        new GetCardBalanceTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                MoneyInfoBean cardInfo = (MoneyInfoBean) o;
                if (!Preconditions.isNullOrEmpty(cardInfo) && !Preconditions.isNullOrEmpty(cardInfo.getAmount())) {
                    cardDetailMoney.setText(cardInfo.getAmount());
                }
            }
        }).execute();
    }

    private void handleCardStatus() {
        switch (cardDetailInfo.getCardtype()) {
            case 0:
                SHelper.vis(cardDetailDelete);
                if (!Preconditions.isNullOrEmpty(cardDetailInfo.getCardno())) {
                    SHelper.vis(cardDetailNum);
                    cardDetailBtnUse.setText("查看密码");
                    cardDetailNum.setText(cardDetailInfo.getCardno());
                } else {
                    SHelper.gone(cardDetailBtnUse, cardDetailBtnLl1);
                }
                SHelper.gone(cardDetailMoneyLl, cardDetailBtnCharge, cardDetailDetailRl, cardDetailDetailLine, cardDetailRechargeRl, cardDetailRechargeLine, cardDetailPurchaseRl, cardDetailPurchaseLine, cardDetailCode);
                break;
            case 1:
                SHelper.vis(cardDetailDelete);
                httpCardUrl = cardDetailInfo.getCardno();
                SHelper.invis(cardDetailNum);
                SHelper.gone(cardDetailMoneyLl, cardDetailBtnCharge, cardDetailDetailRl, cardDetailDetailLine, cardDetailRechargeRl, cardDetailRechargeLine, cardDetailPurchaseRl, cardDetailPurchaseLine, cardDetailCode);
                break;
            case 2:
                cardDetailNum.setText(cardDetailInfo.getCardno());
                cardDetailMoney.setText(cardDetailInfo.getAmount() + "");
                SHelper.gone(cardDetailBtnCharge, cardDetailRechargeRl, cardDetailRechargeLine, cardDetailPurchaseRl, cardDetailPurchaseLine, cardDetailDate, cardDetailDetailRl, cardDetailDetailLine);
                break;
            default:
                SHelper.gone(cardDetailDate);
                cardDetailMoney.setText(cardDetailInfo.getAmount() + "");
                cardDetailNum.setText(cardDetailInfo.getCardno());
        }
    }

    private void showCardDetailInfo() {
        if (!Preconditions.isNullOrEmpty(cardDetailInfo.getColor())) {
            cardDetailParent.setCardBackgroundColor(Color.parseColor(cardDetailInfo.getColor()));
        }

        BaseImageLoaderUtils.getInstance().loadDefaltImage(this, cardDetailImg, cardDetailInfo.getBrandIcon());

        cardDetailName.setText(cardDetailInfo.getBrand());

        if (!Preconditions.isNullOrEmpty(cardDetailInfo.getStartDate()) && !Preconditions.isNullOrEmpty(cardDetailInfo.getStopDate())) {
            cardDetailDate.setText("有效期:" + cardDetailInfo.getStartDate() + "至" + cardDetailInfo.getStopDate());
        } else {
            SHelper.gone(cardDetailDate);
        }
    }

    private void showDeleteDialog(final String cardId) {
        new MaterialDialog.Builder(mActivity)
                .title("提示")
                .content("确定删除卡片吗？")
                .positiveText("不删了")
                .negativeText("删除")
                .negativeColor(ContextCompat.getColor(this,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(this,R.color.positive_color))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        //不删了
                        dialog.dismiss();

                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        //删除
                        deleteCard(cardId);
                        dialog.dismiss();
                    }
                })
                .show();
    }

    private void deleteCard(String cardId) {
        new CardDeleteTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                BaseResponseInfo baseResponseInfo = (BaseResponseInfo) o;
                if (!Preconditions.isNullOrEmpty(baseResponseInfo)) {
                    if (baseResponseInfo.getCode() == 204) {
                        WpToast.l(CardDetailActivity.this, "删除成功");
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        WpToast.l(CardDetailActivity.this, "删除失败");
                    }
                }
            }
        }).execute(cardId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }
}
